import os
from datetime import datetime

from django.core.files.storage import default_storage

from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from django.conf import settings


@csrf_exempt
def upload(request):

    if not request.method == "POST":
        return HttpResponse(status=403)

    res = {
        "success": 0,
        "message": None,
        "url": None,
    }

    upload_file = request.FILES.get("editormd-image-file")

    if not upload_file:
        res["message"] = "Upload Failed"
        return JsonResponse(res)


    djmd_upload_path = getattr(settings, "DJMD_UPLOAD_PATH", "djmd")
    use_date_dirs = getattr(settings, "DJMD_USE_DATE_DIRS", True)
    date_path = "" if not use_date_dirs else datetime.now().strftime('%Y/%m/%d')

    use_date_time_prefix = getattr(settings, "DJMD_USE_DATE_TIME_PREFIX", False)
    file_name_prefix = "" if not use_date_time_prefix else datetime.now().strftime('%Y%m%d_%H%M%S_UTC_')

    file_path = os.path.join(djmd_upload_path, date_path, file_name_prefix + upload_file.name)


    file_storage_name = default_storage.save(file_path, upload_file)
    file_url = default_storage.url(file_storage_name)


    url = "{scheme}://{host}{path}".format(
        scheme=request.scheme,
        host=request.get_host(),
        path=file_url,
    )

    res["success"] = 1
    res["url"] = url


    return JsonResponse(res)

